import {
  FlatList,
  Image,
  StyleSheet,
  Text,
  TextInput,
  TouchableOpacity,
  View
} from "react-native";
import { useCallback, useState } from "react";
import { DictType, LiteratureType, MetaType } from "../util/publicType";
import { literatureDict, literatureList } from "../api";
import { useFocusEffect } from "@react-navigation/native";
import SideTar from "../components/SideTar";
import { initMeta, perSize, windowHeight } from "../util";
import Loading from "../components/Loading";
import renderItem from "../components/LiteratureList";
import Empty from "../components/Empty";
import ListFooter from "../components/ListFooter";

const Literature = () => {
  // 字典状态
  const [dictData, setDictData] = useState<Array<DictType>>([]);

  // 文献数据
  const [data, setData] = useState<Array<LiteratureType>>([]);

  // 筛选参数
  const [name, setName] = useState<string | null>("");

  // 请求id
  const [id, setId] = useState<string>("");

  // 请求加载
  const [isLoading, setIsLoding] = useState<boolean>(true);

  // 分页数据
  const [meta, setMeta] = useState<MetaType>(initMeta);

  // 重置数据
  const resetFunc = () => {
    const v = {
      ...meta,
      currentPage: 1
    };
    setMeta(v);
    return v;
  };

  // 屏幕聚焦时
  useFocusEffect(useCallback(() => {
    getDictData();
    resetFunc();
  }, []));

  // id变化或者首次渲染请求文章列表
  useFocusEffect(useCallback(() => {
    // 防止首次进入，请求两次，因此默认值为""
    if (id) {
      getData(meta, true);
    }
  }, [id]));

  // 字典rq
  const getDictData = () => {
    // 请求字典
    literatureDict().then(r => {
      // 存儲值
      setDictData(r.data);
      // 存储id
      if (r.data.length) {
        setId(r.data[0].id);
      }
    });
  };

  // 请求文献,isClear是否清空原数据
  const getData = (v: MetaType = meta, isClear: boolean = false) => {
    setIsLoding(true);
    literatureList(id, v?.currentPage, name).then(r => {
      setIsLoding(false);
      setMeta(r.meta);
      if (isClear) {
        setData(r.data);
      } else {
        setData(v => [
          ...v,
          ...r.data ?? []
        ]);
      }
    });
  };

  // 触底操作
  const onEndReached = () => {
    if (meta.currentPage < meta.lastPage) {
      setMeta(v => {
        return {
          ...v,
          currentPage: v.currentPage++
        };
      });
      getData();
    }
  };

  // 搜索
  const searchClick = () => {
    const meta = resetFunc();
    getData(meta, true);
  };

  return (
    <View style={styles.box}>
      <Loading isLoading={isLoading} />
      <View style={styles.left}>
        <SideTar data={dictData} id={id} setId={setId} resetFunc={resetFunc} />
      </View>
      <View style={styles.right}>
        {/*搜索*/}
        <View style={styles.searchBox}>
          <View>
            <Image style={styles.searchImg} source={require("../static/search.png")}></Image>
          </View>
          <TextInput
            style={styles.searchInput}
            enablesReturnKeyAutomatically={true}
            placeholder="请输入需要搜索的文献"
            defaultValue={name ?? ""}
            multiline={false}
            onChangeText={v => setName(v)}
            //输入结束
            onEndEditing={searchClick}
          />
          {
            name ? (
              <TouchableOpacity
                style={styles.searchClear}
                activeOpacity={0.6}
                onPress={() => setName("")}
              >
                <Image source={require("../static/close.png")} style={{ width: "70%", height: "70%" }}></Image>
              </TouchableOpacity>
            ) : null
          }
          <TouchableOpacity
            style={styles.searchBtn}
            activeOpacity={0.6}
            onPress={searchClick}
          >
            <Text>
              搜索
            </Text>
          </TouchableOpacity>
        </View>
        {/**/}
        <FlatList
          refreshing={false}
          onRefresh={() => {
            const meta = resetFunc();
            getData(meta, true);
          }
          }
          keyExtractor={item => item.id}
          showsVerticalScrollIndicator={false}
          style={{ marginBottom: 120, marginTop: 10, flex: 1, paddingRight: 5 }}
          renderItem={renderItem} data={data}
          ListEmptyComponent={() => (<Empty />)}
          onEndReachedThreshold={0.1}//设置距离底部多远开始触发
          onEndReached={onEndReached}//触底操作
          ListFooterComponent={() => (<ListFooter isList={meta.currentPage < meta.lastPage} />)}
        />
      </View>
    </View>
  );
};

const styles = StyleSheet.create({
  box: {
    width: "100%",
    minHeight: windowHeight,
    display: "flex",
    flexDirection: "row",
    justifyContent: "space-between",
    position: "relative",
    marginTop: 10
  },
  left: {
    flex: 1,
    maxWidth: "18%",
    minWidth: "18%",
    display: "flex",
    minHeight: windowHeight,
    backgroundColor: "#fff"
  },
  right: {
    flex: 5,
    maxWidth: "80%",
    minWidth: "80%"
  },
  searchBox: {
    backgroundColor: "#fff",
    width: "100%",
    display: "flex",
    flexDirection: "row",
    alignItems: "center",
    justifyContent: "space-between",
    borderRadius: 30,
    paddingLeft: 10
  },
  searchInput: {
    width: "70%",
    backgroundColor: "#fff",
    height: 34,
    fontSize: 12,
    padding: 10,
    paddingLeft: 0,
    paddingRight: 0
  },
  searchBtn: {
    width: "16%",
    fontSize: 16,
    textAlign: "center"
  },
  searchClear: {
    width: 12,
    height: 12,
    borderRadius: 12,
    padding: 1,
    backgroundColor: "#aaa",
    display: "flex",
    justifyContent: "center",
    alignItems: "center"

  },
  searchLeft: {
    width: "10%",
    display: "flex",
    justifyContent: "center"
  },
  searchImg: {
    width: 20,
    height: 20
  }
});

export default Literature;
